package net.cn_su.sharpeyes.activity;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hik.mcrsdk.rtsp.ABS_TIME;
import com.hik.mcrsdk.rtsp.PlaybackInfo;
import com.hik.mcrsdk.rtsp.RtspClient;
import com.hikvision.vmsnetsdk.CameraInfoEx;
import com.hikvision.vmsnetsdk.RecordInfo;
import com.hikvision.vmsnetsdk.ServInfo;
import com.hikvision.vmsnetsdk.VMSNetSDK;
import com.hikvision.vmsnetsdk.netLayer.mag.MAGServer;
import com.hikvision.vmsnetsdk.netLayer.msp.deviceInfo.DeviceInfo;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import net.cn_su.sharpeyes.R;
import net.cn_su.sharpeyes.application.SuApplication;
import net.cn_su.sharpeyes.constants.Constants;
import net.cn_su.sharpeyes.playback.ConstantPlayBack;
import net.cn_su.sharpeyes.playback.PlayBackCallBack;
import net.cn_su.sharpeyes.playback.PlayBackControl;
import net.cn_su.sharpeyes.playback.PlayBackParams;
import net.cn_su.sharpeyes.pref.ServerInfo_;
import net.cn_su.sharpeyes.utils.DebugLog;
import net.cn_su.sharpeyes.utils.NetWorkUtils;
import net.cn_su.sharpeyes.utils.TimerUtil;
import net.cn_su.sharpeyes.utils.UIUtil;
import net.cn_su.sharpeyes.utils.http.HttpClient;
import net.cn_su.sharpeyes.utils.http.HttpUrl;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.util.TextUtils;

/**
 * 播放回看的Activity
 * Created by Overlord on 2016/08/18.
 * Singularity Universe
 */
@Fullscreen
@EActivity(R.layout.activity_playback)
public class PlayBackActivity extends AppCompatActivity implements PlayBackCallBack {
    /**
     * 日志
     */
    private static final String TAG = "PlayBackActivity";

    @ViewById
     LinearLayout ll_time_hour_left;
    /**
     * 控制层对象
     */
    private PlayBackControl mControl;
    /**
     * 创建消息对象
     */
    private Handler mMessageHandler;
    /**
     * 回放时的参数对象
     */
    private PlayBackParams mParamsObj;

    private VMSNetSDK mVmsNetSDK = null;
    private String mDeviceID = "";
    private ServInfo mServInfo;
    /**
     * 监控点详细信息对象
     */
    private CameraInfoEx cameraInfoEx;
    /**
     * 获取监控点详情结果
     */
    private boolean getCameraDetailInfoResult = false;
    /**
     * 获取设备详情结果
     */
    private boolean getDeviceInfoResult = false;
    private DeviceInfo deviceInfo;
    private String serAddr = null;
    private String sessionId = null;

    private Calendar mPlaybackTime = null;
    // 录像存储介质
    private int mPlaybackMedium = -1;
    private List<Integer> mPlaybackMediums = null;

    /**
     * 回放地址
     */
    private String mPlaybackUrl = "";
    private RecordInfo mRecordInfo = null;

    /**
     * 播放视图控件
     */
    @ViewById
    protected SurfaceView mSurfaceView;
    @ViewById
    protected ProgressBar progressBar;
    @ViewById
    protected TextView tv_year, tv_month, tv_day, tv_hour, tv_minute, textView_camera, textView_camera_address;

    @ViewById
    protected LinearLayout btn_full, btn_exit_full;

    @ViewById
    protected LinearLayout layout_right;
    @ViewById
    protected RelativeLayout layout_left;

    // 每次操作分钟的增量
    private final int SEC_INCREMENT = 10;
    // 每次操作小时的增量
    private final int HOUR_INCREMENT = 1;


    private int currentYear = 0;
    private int currentMonth = 0;
    private int currentDay = 0;
    private int currentHour = 0;
    private int currentMinute = 0;

    @Extra
    protected String cameraID, cameraName, cameraAddress;
    @App
    protected SuApplication suApplication;
    @Pref
    protected ServerInfo_ serverInfo;


    //是否点击了确认按钮
    private boolean isCheck = false;
    //是否获取录像成功
    private boolean flag = false;


    private long systemTime = System.currentTimeMillis();

    /**
     * 右边菜单的宽度
     */
    private int rWidth=0;
    /**
     * 左边视频的宽度
     */
    private int lWidth;
    /**
     * 屏幕的宽度
     */
    private int dWidth;

    /**
     * 音频是否开启
     */
    private boolean mIsStartAudio=false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dWidth = this.getWindowManager().getDefaultDisplay().getWidth();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        initPlayBack();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (flag&&mControl!=null&&mIsStartAudio){
            mControl.stopAudio();
        }
        flag = false;
        stopPlayback();
    }

    /**
     * 初始化回放
     */
    private void initPlayBack() {


        mMessageHandler = new MyHandler();
        // 创建和cms平台交互的对象
        mVmsNetSDK = VMSNetSDK.getInstance();
        // 初始化远程回放控制层对象
        mControl = new PlayBackControl();
        // 设置远程回放控制层回调
        mControl.setPlayBackCallBack(this);
        // 创建远程回放需要的参数
        mParamsObj = new PlayBackParams();

        serAddr = serverInfo.serverAddress().get();
        mServInfo = suApplication.getServInfo();
        sessionId = mServInfo.getSessionID();


    }

    /**
     * 初始化控件相关
     */
    @AfterViews
    protected void initUI() {
        textView_camera.setText("-" + cameraName);
        textView_camera_address.setText(cameraAddress);

       /* Handler handler=new Handler();

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

            }
        },3000);*/
        ll_time_hour_left.requestFocus();



        getSystemTimeInit();


    }

    private void getSystemTimeInit() {

        HttpClient.get(HttpUrl.GET_SERVICE_TIME, null, new BaseJsonHttpResponseHandler() {


            @Override
            public void onFinish() {
                super.onFinish();
              //  Logger.d("onfinish==="+systemTime);


            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Object response) {
             //   Logger.d("responseString==" + rawJsonResponse);
                systemTime = Long.parseLong(rawJsonResponse);
                // 处理选择回放的默认时间
                Calendar calendar = Calendar.getInstance();

                calendar.setTimeInMillis(systemTime);

                currentYear = calendar.get(Calendar.YEAR);
                currentMonth = calendar.get(Calendar.MONTH);
                currentDay = calendar.get(Calendar.DAY_OF_MONTH);
                currentHour = calendar.get(Calendar.HOUR_OF_DAY);
                currentMinute = calendar.get(Calendar.MINUTE);
                currentMonth += 1;
                currentMinute = currentMinute - currentMinute % 10;

                tv_year.setText(currentYear + "年");
                tv_month.setText(String.format(Locale.ENGLISH, "%02d", currentMonth) + "月");
                tv_day.setText(String.format(Locale.ENGLISH, "%02d", currentDay) + "日");
                tv_hour.setText(String.format(Locale.ENGLISH, "%02d", currentHour) + "时");
                tv_minute.setText(String.format(Locale.ENGLISH, "%02d", currentMinute) + "分");

                // 播放控件
                mParamsObj.surfaceView = mSurfaceView;

                cameraInfoEx = new CameraInfoEx();
                cameraInfoEx.setId(cameraID);


                mPlaybackTime = Calendar.getInstance();
                mPlaybackTime.setTimeInMillis(systemTime);
                mPlaybackTime.set(Calendar.HOUR_OF_DAY, 0);
                mPlaybackTime.set(Calendar.MINUTE, 0);
                mPlaybackTime.set(Calendar.SECOND, 0);
                mPlaybackTime.set(Calendar.MILLISECOND, 0);

                queryPlaybackInfo();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, Object errorResponse) {
                // 处理选择回放的默认时间
                Calendar calendar = Calendar.getInstance();

                calendar.setTimeInMillis(systemTime);

                currentYear = calendar.get(Calendar.YEAR);
                currentMonth = calendar.get(Calendar.MONTH);
                currentDay = calendar.get(Calendar.DAY_OF_MONTH);
                currentHour = calendar.get(Calendar.HOUR_OF_DAY);
                currentMinute = calendar.get(Calendar.MINUTE);
                currentMonth += 1;
                currentMinute = currentMinute - currentMinute % 10;

                tv_year.setText(currentYear + "年");
                tv_month.setText(String.format(Locale.ENGLISH, "%02d", currentMonth) + "月");
                tv_day.setText(String.format(Locale.ENGLISH, "%02d", currentDay) + "日");
                tv_hour.setText(String.format(Locale.ENGLISH, "%02d", currentHour) + "时");
                tv_minute.setText(String.format(Locale.ENGLISH, "%02d", currentMinute) + "分");

                // 播放控件
                mParamsObj.surfaceView = mSurfaceView;

                cameraInfoEx = new CameraInfoEx();
                cameraInfoEx.setId(cameraID);


                mPlaybackTime = Calendar.getInstance();
                mPlaybackTime.setTimeInMillis(systemTime);
                mPlaybackTime.set(Calendar.HOUR_OF_DAY, 0);
                mPlaybackTime.set(Calendar.MINUTE, 0);
                mPlaybackTime.set(Calendar.SECOND, 0);
                mPlaybackTime.set(Calendar.MILLISECOND, 0);

                queryPlaybackInfo();

            }

            @Override
            protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                return null;
            }
        });


    }

    private void getSystemTime() {

        HttpClient.get(HttpUrl.GET_SERVICE_TIME, null, new BaseJsonHttpResponseHandler() {


            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Object response) {
                //Logger.d("responseString==" + rawJsonResponse);
                systemTime = Long.parseLong(rawJsonResponse);

                if (systemTime < mPlaybackTime.getTimeInMillis()) {
                    UIUtil.showToast(PlayBackActivity.this, "回放时间不能超过当前时间");
                    return;
                }
                startPlayback(mPlaybackTime);

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, Object errorResponse) {
                UIUtil.showToast(PlayBackActivity.this, "网络连接错误");

            }

            @Override
            protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                return null;
            }
        });


    }

    /**
     * 增加小时
     */
    @Click(R.id.ll_time_hour_right)
    protected void hourAddClick() {
        hourHandle(true);
    }

    /**
     * 减少小时
     */
    @Click(R.id.ll_time_hour_left)
    protected void hourDecreaseClick() {
        hourHandle(false);
    }


    /**
     * 小时操作
     *
     * @param isAdd true表示增加时间
     */
    private void hourHandle(boolean isAdd) {
        if (isAdd) {
            // 添加小时
            currentHour = (currentHour + HOUR_INCREMENT) % 24;

        } else {
            if (currentHour == 0) {
                currentHour = 24 - HOUR_INCREMENT;
            } else {
                currentHour -= HOUR_INCREMENT;
            }
        }
        tv_hour.setText(String.format(Locale.ENGLISH, "%02d", currentHour) + "时");
    }

    /**
     * 增加分钟
     */
    @Click(R.id.ll_time_minute_right)
    protected void secAddClick() {
        secHandle(true);
    }

    /**
     * 减少分钟
     */
    @Click(R.id.ll_time_minute_left)
    protected void secDecreaseClick() {
        secHandle(false);
    }

    /**
     * 分钟操作
     *
     * @param isAdd true表示增加时间
     */
    private void secHandle(boolean isAdd) {
        if (isAdd) {
            // 添加分钟
            currentMinute = (currentMinute + SEC_INCREMENT) % 60;


        } else {
            if (currentMinute == 0) {
                currentMinute = 50;
            } else {
                currentMinute -= SEC_INCREMENT;
            }
        }

        tv_minute.setText(String.format(Locale.ENGLISH, "%02d", currentMinute) + "分");
    }

    /**
     * 增加年
     */
    @Click(R.id.ll_time_year_right)
    protected void yearAddClick() {
        yearHandle(true);
    }

    /**
     * 减少年
     */
    @Click(R.id.ll_time_year_left)
    protected void yearDecreaseClick() {
        yearHandle(false);
    }

    /**
     * 年操作
     *
     * @param isAdd true表示增加时间
     */
    private void yearHandle(boolean isAdd) {
        if (isAdd) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(systemTime);
            // 添加年
            if (currentYear < calendar.get(Calendar.YEAR)) {
                currentYear += 1;
            } else {
                currentYear = calendar.get(Calendar.YEAR);
            }

        } else {
            if (currentYear > 1990) {
                currentYear--;
            } else {
                currentYear = 1990;
            }

        }

        tv_year.setText(currentYear + "年");
        updateDay(currentYear, currentMonth);
    }

    /**
     * 增加月
     */
    @Click(R.id.ll_time_month_right)
    protected void monthAddClick() {
        monthHandle(true);
    }

    /**
     * 减少月
     */
    @Click(R.id.ll_time_month_left)
    protected void monthDecreaseClick() {
        monthHandle(false);
    }

    /**
     * 月操作
     *
     * @param isAdd true表示增加时间
     */
    private void monthHandle(boolean isAdd) {
        if (isAdd) {
            // 添加月
            currentMonth = ((currentMonth + 1) % 12) == 0 ? currentMonth + 1 : (currentMonth + 1) % 12;

        } else {
            if (currentMonth == 1) {
                currentMonth = 12;
            } else {
                currentMonth -= 1;
            }
        }
        tv_month.setText(String.format(Locale.ENGLISH, "%02d", currentMonth) + "月");
        updateDay(currentYear, currentMonth);
    }


    /**
     * 增加日
     */
    @Click(R.id.ll_time_day_right)
    protected void dayAddClick() {
        dayHandle(true);
    }

    /**
     * 减少日
     */
    @Click(R.id.ll_time_day_left)
    protected void dayDecreaseClick() {
        dayHandle(false);

    }

    /**
     * 日操作
     *
     * @param isAdd true表示增加时间
     */
    private void dayHandle(boolean isAdd) {
        if (isAdd) {
            // 添加日
            currentDay = ((currentDay + 1) % getMaxDay(currentYear, currentMonth)) == 0 ? currentDay + 1 : (currentDay + 1) % getMaxDay(currentYear, currentMonth);
        } else {
            if (currentDay == 1) {
                currentDay = getMaxDay(currentYear, currentMonth);
            } else {
                currentDay -= 1;
            }
        }
        tv_day.setText(String.format(Locale.ENGLISH, "%02d", currentDay) + "日");
    }

    /**
     * 当年月发生变化，有可能会更新天
     *
     * @param year
     * @param month
     */
    private void updateDay(int year, int month) {
        if (getMaxDay(year, month) < currentDay) {
            currentDay = getMaxDay(year, month);
            tv_day.setText(String.format(Locale.ENGLISH, "%02d", currentDay) + "日");
        }

    }


    private int getMaxDay(int year, int month) {

        int maxDay = 30;

        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
            maxDay = 31;
        } else {
            if (month != 2) {
                maxDay = 30;
            } else {
                maxDay = year % 4 == 0 ? 29 : 28;
            }

        }


        return maxDay;
    }


    /**
     * 确认回放时间进行回放
     */
    @Click(R.id.btn_confirm)
    protected void confirmTimeToPlay() {

        //判断有无网络连接
        if (!NetWorkUtils.isNetworkConnected(this)) {
            UIUtil.showToast(this, "网络连接不可用");
            return;
        }

        isCheck = true;
        if (mPlaybackTime == null) {
            mPlaybackTime = Calendar.getInstance();
            mPlaybackTime.setTimeInMillis(systemTime);
        }

        mPlaybackTime.set(Calendar.HOUR_OF_DAY, currentHour);
        mPlaybackTime.set(Calendar.YEAR, currentYear);
        mPlaybackTime.set(Calendar.MONTH, currentMonth - 1);
        mPlaybackTime.set(Calendar.DAY_OF_MONTH, currentDay);
        mPlaybackTime.set(Calendar.MINUTE, currentMinute);
        mPlaybackTime.set(Calendar.SECOND, 0);
        mPlaybackTime.set(Calendar.MILLISECOND, 0);

        getSystemTime();


    }

    /**
     * 退回到上一页
     */
    @Click(R.id.btn_back)
    protected void back() {
        PlayBackActivity.this.finish();
    }


    /**
     * 播放回放
     *
     * @param startCalendar
     */
    //    @Background
    protected void startPlayback(Calendar startCalendar) {
        UIUtil.showToast(PlayBackActivity.this, "播放" + TimerUtil.getTime_hhmm(startCalendar) + "的录像");
        if (null != mControl) {
            setPlaybackUrl(mRecordInfo.segmentListPlayUrl, startCalendar, getEndCalendar(startCalendar));
            mParamsObj.url = mPlaybackUrl;
            if (mControl.PLAYBACK_PLAY == mControl.getPlayBackState()) {
                mControl.stopPlayBack();
            }

            if (mControl.PLAYBACK_INIT == mControl.getPlayBackState()
                    || mControl.PLAYBACK_RELEASE == mControl.getPlayBackState()) {
                mControl.startPlayBack(mParamsObj);
            }
        }
    }

    /**
     * 停止视频播放
     */
    @Background
    protected void stopPlayback() {
        mControl.stopPlayBack();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (null != mPlaybackTime && isCheck)
            startPlayback(mPlaybackTime);
    }

    /**
     * 获取回放的结束时间
     *
     * @param startCalendar 起始时间
     * @return
     */
    private Calendar getEndCalendar(Calendar startCalendar) {
        Calendar endCalendar = Calendar.getInstance();
        Calendar _calendar = startCalendar != null ? startCalendar : Calendar.getInstance();
        endCalendar.setTimeInMillis(_calendar.getTimeInMillis() + 24 * 3600 * 1000 - 1000);
        return endCalendar;
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus&&rWidth==0) {
            rWidth = layout_right.getWidth();
            mSurfaceView.getLayoutParams().width = dWidth - rWidth;
            layout_left.setLayoutParams(mSurfaceView.getLayoutParams());
            mSurfaceView.setLayoutParams(mSurfaceView.getLayoutParams());
            lWidth = dWidth - rWidth;


        }
    }
    /**
     * 点击全屏按钮
     */
    @Click(R.id.btn_full)
    protected void inhFullScreen() {

        if (!isCheck||!flag){
            return;
        }
        // 全屏显示
        //   layout_right.setVisibility(View.GONE);
        btn_full.setVisibility(View.GONE);
        btn_exit_full.setVisibility(View.VISIBLE);

        layout_left.getLayoutParams().width = dWidth;
        layout_left.setLayoutParams(layout_left.getLayoutParams());
        ValueAnimator valueAnimator = new ValueAnimator();
        valueAnimator.setFloatValues(0, rWidth);
        valueAnimator.setDuration(500);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                layout_right.setTranslationX(value);

            }
        });
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                btn_exit_full.requestFocus();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        valueAnimator.start();
    }

    /**
     * 退出全屏按钮
     */
    @Click(R.id.btn_exit_full)
    protected void exitFullScreen() {
        // 退出全屏

        btn_full.setVisibility(View.VISIBLE);
        btn_exit_full.setVisibility(View.GONE);

        ValueAnimator valueAnimator = new ValueAnimator();
        valueAnimator.setFloatValues(rWidth, 0);
        valueAnimator.setDuration(500);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                layout_right.setTranslationX(value);
            }
        });
        valueAnimator.start();
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                layout_left.getLayoutParams().width = lWidth;
                layout_left.setLayoutParams(layout_left.getLayoutParams());
                btn_full.requestFocus();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }


    // ------------------------------------------以下是海康代码------------------------------------

    /**
     * 进行远程回放录像查询
     *
     * @since V1.0
     */
    public void queryPlaybackInfo() {
        new Thread(new Runnable() {

            @Override
            public void run() {

                getCameraDetailInfoResult = PlayBackActivity.this.mVmsNetSDK.getCameraInfoEx(serAddr, sessionId,
                        cameraID, cameraInfoEx);
                Log.i(Constants.LOG_TAG, "result is :" + getCameraDetailInfoResult);

                mDeviceID = cameraInfoEx.getDeviceId();
                Log.i(Constants.LOG_TAG, "mDeviceID is :" + mDeviceID);
                deviceInfo = new DeviceInfo();

                //获取设备信息
                getDeviceInfoResult = PlayBackActivity.this.mVmsNetSDK.getDeviceInfo(serAddr, sessionId, mDeviceID, deviceInfo);
                if (!getDeviceInfoResult || null == deviceInfo || deviceInfo.equals("")) {
                    deviceInfo.setLoginName(serverInfo.hikAccount().get());
                    deviceInfo.setLoginPsw(serverInfo.hikPassword().get());
                }

                mParamsObj.name = deviceInfo.getLoginName();
                mParamsObj.passwrod = deviceInfo.getLoginPsw();

                DebugLog.info(Constants.LOG_TAG, "ret is :" + getDeviceInfoResult + "----------------"
                        + deviceInfo.getDeviceName() + "--------"
                        + "deviceLoginName is " + mParamsObj.name + "---"
                        + "deviceLoginPassword is " + mParamsObj.passwrod + "-----"
                        + "deviceID is " + mDeviceID);

                // 这里是查询录像记录的起始时间
                Calendar mStartCalendar = Calendar.getInstance();
                /* 其他回放录像,默认回放起始时间为0 */
                mStartCalendar.setTimeInMillis(mPlaybackTime.getTimeInMillis());
                Log.d(TAG, "queryPlaybackTimes,startTimeCalendar:" + TimerUtil.getTime_nnnnyydd(mStartCalendar));

                /* 回放结束时间重置为起始时间后的23小时59分59秒 */
                Calendar mEndCalendar = getEndCalendar(mStartCalendar);
                //                mEndCalendar.setTimeInMillis(mStartCalendar.getTimeInMillis() + 24 * 3600 * 1000 - 1000);
                Log.d(TAG, "queryPlaybackTimes,endTimeCalendar:" + TimerUtil.getTime_nnnnyydd(mEndCalendar));

                // 查询录像库中的时间对象，注意Calendar时间，使用前请先了解下Calendar
                com.hikvision.vmsnetsdk.ABS_TIME startTime = new com.hikvision.vmsnetsdk.ABS_TIME(mStartCalendar);
                com.hikvision.vmsnetsdk.ABS_TIME endTime = new com.hikvision.vmsnetsdk.ABS_TIME(mEndCalendar);

                setParamsObjTime(startTime, endTime);
                mRecordInfo = new RecordInfo();
                if (mVmsNetSDK == null) {
                    Log.e(Constants.LOG_TAG, "mVmsNetSDK is " + null);
                    return;
                }

                boolean ret = queryRecord(startTime, endTime, mRecordInfo);
                if (!ret) {
                    Log.e(TAG, "queryPlaybackTimes queryRecordByMedium fail");
                    return;
                }

                if (mRecordInfo != null) {
                    Log.i(Constants.LOG_TAG, "segmentListPlayUrl : " + mRecordInfo.segmentListPlayUrl);
                }
            }
        }).start();
    }

    private boolean queryRecord(com.hikvision.vmsnetsdk.ABS_TIME startTime
            , com.hikvision.vmsnetsdk.ABS_TIME endTime, RecordInfo recordInfo) {

        if (startTime == null || endTime == null) {
            Log.e(TAG, "queryPlaybackTimes play time is null");
            return false;
        }

        if (recordInfo == null) {
            Log.e(TAG, "queryPlaybackTimes recordInfo == null");
            return false;
        }
        // cms平台地址
        String servHeadAddr = mServInfo.getMagServer().getMagHttpRequestAddrHead(true);
        Log.e(TAG, "servHeadAddr == " + servHeadAddr);
        // 查询的录像类型，1-计划录像，2-移动录像，16-手动录像，4-报警录像
        String recordType = "1,2,4,16";


        if (null == cameraInfoEx) {
            return false;
        }
        List<Integer> recordPoses = cameraInfoEx.getRecordPos();
        if ((null == recordPoses)) {
            Log.e(TAG, "queryPlaybackTimes queryCameraRecord null == recordPos");
            sendToastMessage(getString(R.string.playback_not_allot_record));
            return false;
        }
        Log.e(TAG, "recordPos.size() == " + recordPoses.size());
        mPlaybackMediums = recordPoses;
        int i = 0;
        while (true) {

            /* 查询录像失败 */
            if (i == recordPoses.size()) {
                /* 查询录像失败 */
                int errorCode = PlayBackActivity.this.mVmsNetSDK.getLastErrorCode();
                if (errorCode == VMSNetSDK.VMSNETSDK_MSP_NO_DATA) {
              //      Logger.e("查询录像失败，没有录像文件");
                } else if (errorCode == VMSNetSDK.VMSNETSDK_MSP_SESSION_ERROR) {
                //    Logger.e("查询录像失败，sessionid异常");
                } else {
                //    Logger.e("查询录像失败，错误码：" + PlayBackActivity.this.mVmsNetSDK.getLastErrorCode());
                }
              //  Logger.e("queryPlaybackTimes queryCameraRecord fail, errorCode:" + PlayBackActivity.this.mVmsNetSDK.getLastErrorCode());

                sendMessageCase(ConstantPlayBack.GET_RECORD_FILE_FAIL);
                return false;
            }

            mPlaybackMedium = recordPoses.get(i);
            recordInfo.recSegmentList.clear();
            boolean ret = PlayBackActivity.this.mVmsNetSDK.queryCameraRecord(servHeadAddr, sessionId, cameraID, recordType,
                    String.valueOf(mPlaybackMedium), startTime, endTime, recordInfo);
            if (ret) {
         //       Logger.e("queryPlaybackTimes queryCameraRecord success, mPlaybackMediums:" + mPlaybackMediums);
                break;
            }

            i++;
        }

        sendMessageCase(ConstantPlayBack.GET_RECORD_FILE_SUCCESS);


        return true;
    }


    private void setPlaybackUrl(String url, Calendar startTime, Calendar endTime) {
        if (null == url || url.equals("") || null == startTime || null == endTime) {
            return;
        }
        String mToken = null;
        if (mServInfo != null && mServInfo.isTokenVerify()) {
            //获取播放Token
            mToken = PlayBackActivity.this.mVmsNetSDK.getPlayToken(mServInfo.getSessionID());
            DebugLog.info(Constants.LOG_TAG, "mToken is :" + mToken);
        }
        if (TextUtils.isEmpty(deviceInfo.getLoginPsw()) || TextUtils.isEmpty(deviceInfo.getLoginName())) {
            deviceInfo.setLoginName(serverInfo.hikAccount().get());
            deviceInfo.setLoginPsw(serverInfo.hikPassword().get());
        }
        //start add by zhoujian reason:支持大华设备录像回放查询
        String begin = getPlaybackTime(startTime);
        String end = getPlaybackTime(endTime);

        if (mServInfo != null) {
            PlaybackInfo playbackInfo = new PlaybackInfo();
            MAGServer magserver = mServInfo.getMagServer();
            if (magserver != null && magserver.getMagStreamSerAddr() != null) {
                playbackInfo.setMagIp(magserver.getMagStreamSerAddr());
                playbackInfo.setMagPort(magserver.getMagStreamSerPort());
                Log.d(TAG, "setPlaybackUrl magIP:" + magserver.getMagStreamSerAddr());
                Log.d(TAG, "setPlaybackUrl magPort:" + magserver.getMagStreamSerPort());
            }
            int magVersion = VMSNetSDK.getInstance().isNewMagVersion();
            Log.d(TAG, "setPlaybackUrl MAGVersion:" + magVersion);
            playbackInfo.setMagVersion(magVersion);

            playbackInfo.setPlaybackUrl(url);
            if (mToken != null) {
                playbackInfo.setToken(mToken);
            }
            playbackInfo.setBegin(begin);
            playbackInfo.setEnd(end);

            Log.d(TAG, "setPlaybackUrl url:" + url);
            Log.d(TAG, "setPlaybackUrl token:" + mToken);

            mPlaybackUrl = RtspClient.getInstance().generatePlaybackUrl(playbackInfo);
            Log.e(TAG, "setPlaybackUrl() RtspClient.getInstance().generatePlaybackUrl(playbackInfo):" + mPlaybackUrl);
        }
        mPlaybackUrl =
                mPlaybackUrl + "|&startTime=" + startTime.getTimeInMillis() + "&endTime=" + endTime.getTimeInMillis()
                        + "&deviceName=" + deviceInfo.getLoginName() + "&devicePassword=" + deviceInfo.getLoginPsw();
        Log.e(TAG, "setPlaybackUrl() PlaybackUrl:" + mPlaybackUrl);
    }


    /**
     * 设置远程回放取流的开始时间和结束时间
     *
     * @param startTime
     * @param endTime
     * @since V1.0
     */
    protected void setParamsObjTime(com.hikvision.vmsnetsdk.ABS_TIME startTime, com.hikvision.vmsnetsdk.ABS_TIME endTime) {
        if (startTime == null || endTime == null) {
            Log.e(Constants.LOG_TAG, "setParamsObjTime():: startTime is " + startTime + "endTime is " + endTime);
        }
        // 取流库中的时间对象
        ABS_TIME rtspEndTime = new ABS_TIME();
        ABS_TIME rtspStartTime = new ABS_TIME();

        // 设置播放结束时间
        rtspEndTime.setYear(endTime.dwYear);
        // 之所以要加1，是由于我们查询接口中的时间和取流中的时间采用的是两个自定义的时间类，这个地方开发者按照demo中实现就可以了。
        rtspEndTime.setMonth(endTime.dwMonth + 1);
        rtspEndTime.setDay(endTime.dwDay);
        rtspEndTime.setHour(endTime.dwHour);
        rtspEndTime.setMinute(endTime.dwMinute);
        rtspEndTime.setSecond(endTime.dwSecond);

        // 设置开始播放时间
        rtspStartTime.setYear(startTime.dwYear);
        // 之所以要加1，是由于我们查询接口中的时间和取流中的时间采用的是两个自定义的时间类，这个地方开发者按照demo中实现就可以了。
        rtspStartTime.setMonth(startTime.dwMonth + 1);
        rtspStartTime.setDay(startTime.dwDay);
        rtspStartTime.setHour(startTime.dwHour);
        rtspStartTime.setMinute(startTime.dwMinute);
        rtspStartTime.setSecond(startTime.dwSecond);

        if (mParamsObj != null) {
            // 设置开始远程回放的开始时间和结束时间。
            mParamsObj.endTime = rtspEndTime;
            mParamsObj.startTime = rtspStartTime;
        }
    }


    @Override
    public void onMessageCallback(int message) {
        sendMessageCase(message);
    }

    /**
     * 发送消息
     *
     * @param i void
     * @since V1.0
     */
    private void sendMessageCase(int i) {
        if (null != mMessageHandler) {
            Message msg = Message.obtain();
            msg.arg1 = i;
            mMessageHandler.sendMessage(msg);
        }
    }

    @SuppressLint("HandlerLeak")
    class MyHandler extends Handler {
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case ConstantPlayBack.START_RTSP_SUCCESS:
                    UIUtil.showToast(PlayBackActivity.this, "启动取流库成功");
                    break;

                case ConstantPlayBack.START_RTSP_FAIL:
                    UIUtil.showToast(PlayBackActivity.this, "启动取流库失败");
                    if (null != progressBar) {
                        progressBar.setVisibility(View.GONE);
                    }
                    upError("启动取流库失败");
                    break;

                case ConstantPlayBack.PAUSE_SUCCESS:
                    UIUtil.showToast(PlayBackActivity.this, "暂停成功");
                    //                    mPauseButton.setText("恢复");
                    //                    mIsPause = true;
                    break;

                case ConstantPlayBack.PAUSE_FAIL:
                    UIUtil.showToast(PlayBackActivity.this, "暂停失败");
                    //                    mPauseButton.setText("暂停");
                    //                    mIsPause = false;

                    break;

                case ConstantPlayBack.RESUEM_FAIL:
                    UIUtil.showToast(PlayBackActivity.this, "恢复播放失败");
                    //                    mPauseButton.setText("恢复");
                    //                    mIsPause = true;
                    break;

                case ConstantPlayBack.RESUEM_SUCCESS:
                    UIUtil.showToast(PlayBackActivity.this, "恢复播放成功");
                    //                    mPauseButton.setText("暂停");
                    //                    mIsPause = false;
                    break;

                case ConstantPlayBack.START_OPEN_FAILED:
                    UIUtil.showToast(PlayBackActivity.this, "启动播放库失败");
                    if (null != progressBar) {
                        progressBar.setVisibility(View.GONE);
                    }
                    upError("启动播放库失败");
                    break;

                case ConstantPlayBack.PLAY_DISPLAY_SUCCESS:
                    flag=true;
                    mIsStartAudio=mControl.startAudio();
                   /* if (! mControl.startAudio()){

                    }*/
                    if (null != progressBar) {
                        progressBar.setVisibility(View.GONE);
                    }
                    break;
                case ConstantPlayBack.CAPTURE_FAILED_NPLAY_STATE:
                    UIUtil.showToast(PlayBackActivity.this, "非播放状态不能抓怕");
                    break;
                case ConstantPlayBack.PAUSE_FAIL_NPLAY_STATE:
                    UIUtil.showToast(PlayBackActivity.this, "非播放状态不能暂停");
                    break;
                case ConstantPlayBack.RECORD_FAIL_NPLAY_STATE:
                    UIUtil.showToast(PlayBackActivity.this, "非播放状态不能录像");
                    break;
                case ConstantPlayBack.AUDIO_START_FAIL_NPLAY_STATE:
                    UIUtil.showToast(PlayBackActivity.this, "非播放状态不能开启音频");
                    break;
                case ConstantPlayBack.RESUEM_FAIL_NPAUSE_STATE:
                    UIUtil.showToast(PlayBackActivity.this, "非播放状态");
                    break;
                case ConstantPlayBack.GET_RECORD_FILE_SUCCESS:
                    UIUtil.showToast(PlayBackActivity.this, "获取录像文件成功");
                    if (null != progressBar) {
                        progressBar.setVisibility(View.GONE);
                    }
                    //                    mStartButton.setEnabled(true);
                    //                    mStopButton.setEnabled(true);
                    //                    mPauseButton.setEnabled(true);
                    //                    mCaptureButton.setEnabled(true);
                    //                    mRecordButton.setEnabled(true);
                    //                    mAudioButton.setEnabled(true);
                    break;
                case ConstantPlayBack.GET_RECORD_FILE_FAIL:
                    UIUtil.showToast(PlayBackActivity.this, "获取录像文件失败");
                    if (null != progressBar) {
                        progressBar.setVisibility(View.GONE);
                    }
                    upError("获取录像文件失败");
                    break;
                case ConstantPlayBack.STOP_SUCCESS:
                    //Logger.v("停止成功");
                    break;
                case RtspClient.RTSPCLIENT_MSG_CONNECTION_EXCEPTION:
                    if (null != progressBar) {
                        progressBar.setVisibility(View.GONE);
                    }
                    UIUtil.showToast(PlayBackActivity.this, "RTSP链接异常");
                    upError("RTSP链接异常");
                    break;
                case ConstantPlayBack.SHOW_TOARST:
                    showToast((String) msg.obj);
                    if (null != progressBar) {
                        progressBar.setVisibility(View.INVISIBLE);
                    }
                    break;

            }
        }
    }

    /**
     * 发送消息
     *
     * @param messageStr
     * @since V1.0
     */
    private void sendToastMessage(String messageStr) {
        Message msg = Message.obtain();
        msg.arg1 = ConstantPlayBack.SHOW_TOARST;
        msg.obj = messageStr;

        if (null != mMessageHandler) {
            mMessageHandler.sendMessage(msg);
        }
    }

    private void showToast(String notice) {
        if (!isFinishing()) {
            Toast aToast = Toast.makeText(this, notice, Toast.LENGTH_SHORT);
            //            aToast.setDuration(1000);
            aToast.setGravity(Gravity.CENTER, 0, 0);
            aToast.show();
        }
    }

    //格式化时间数据
    private String getPlaybackTime(Calendar calendar) {
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        String format_month = formatDate(month);//格式为00;
        String format_day = formatDate(day);//格式为00;
        String format_hour = formatDate(hour);//格式为00;
        String format_minute = formatDate(minute);//格式为00;
        String format_second = formatDate(second);//格式为00;
        StringBuffer buffer = new StringBuffer();
        buffer.append(year)
                .append(format_month)
                .append(format_day)
                .append("T")
                .append(format_hour)
                .append(format_minute)
                .append(format_second)
                .append("Z");
        Log.i(TAG, "getPlaybackTime() time::" + buffer.toString());
        return buffer.toString();
    }

    private String formatDate(int date) {
        String format_date = "" + date;
        if (date < 10) {
            format_date = "0" + date;
        }
        return format_date;
    }

    /**
     * 上传错误
     */
    private void upError(String errorMessage) {

        RequestParams params = new RequestParams();
        params.add("user_id", serverInfo.userId().get() + "");
        params.add("debug_call_name", getResources().getString(R.string.back_tip));
        params.add("debug_call_content", errorMessage);
        params.add("app_key", getResources().getString(R.string.mobile_type));
        HttpClient.post(PlayBackActivity.this, HttpUrl.APP_DEBUG_CALL, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                //Logger.v("日志上传成功");

            }


            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {


            }
        });
    }
}
